<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{prop:'timeOfEntry', order: 'ascending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template #default="{row}">
              <img :src="row.staffPhoto" alt="" style="width:100%">
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ formOfEmploymetnFormat(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <!-- <el-button type="text" size="small" @click="$router.push('/employees/detail')">查看</el-button> -->
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <!-- <el-button type="text" size="small" @click="$router.push(`/employees/detail/?id=${row.id}`)">查看</el-button> -->
              <el-button type="text" size="small" @click="assignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 3, 5, 10]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>

      <!-- 新增员工弹层 -->
      <el-dialog
        title="新增员工"
        :visible.sync="showDialog"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        @close="hResetForm"
      >
        <AddEmployees ref="addRef" @close="showDialog = false" @success="hSuccess" />
      </el-dialog>

      <!-- 分配角色 -->
      <el-dialog title="分配角色" :visible.sync="roleShowDialog">
        <assignRole v-if="roleShowDialog" :id="curId" @success="hAssignRoleSuccess" @close="roleShowDialog=false" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import AddEmployees from './empDialog.vue'
import { getEmployees, delEmployee } from '@/api/employees'
import EmployeesEnum from '@/constant/employees'
import assignRole from './assignRole.vue'
// const hireType = {}
// EmployeesEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })
const hireType = EmployeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})

export default {
  name: 'Employees',
  components: {
    AddEmployees,
    assignRole
  },
  data() {
    return {
      roleShowDialog: false,
      // 显示与隐藏弹层
      showDialog: false,
      page: 1,
      size: 2,
      // 员工列表
      list: [],
      total: 0, // 员工总数
      curId: '' // 员工id
    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    // 确定修改角色
    hAssignRoleSuccess() {
      this.roleShowDialog = false
    },
    // 分配角色
    assignRole(id) {
      this.curId = id
      this.roleShowDialog = true
    },
    // 英文转为中文
    transToZh(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const one = list[0]
      console.log('one', one)
      if (!one) return // 木有数据
      const header = Object.keys(one).map(enkey => {
        return map[enkey]
      })
      const data = list.map(item => {
        const keys = item.formOfEmployment
        item['formOfEmployment'] = hireType[keys] || '未知'
        return Object.values(item)
      })
      return { header, data }
    },
    async handleDownload() {
      try {
        const res = await getEmployees(this.page, this.size)
        console.log(res.data.rows)
        console.log(this.transToZh(res.data.rows))
        const { header, data } = this.transToZh(res.data.rows)
        // import('@/vendor/Export2Excel') 懒加载的方式导入一个模块(文件)返回值的一个promise实例
        import('@/vendor/Export2Excel').then(excel => {
        // excel 指的是模块对象, 可以使用excel调用 Export2Excel文件中的函数或者使用Export2Excel文件中的变量
          excel.export_json_to_excel({
            header: header,
            data: data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
        })
        // 保存到data函数中
        this.list = res.data.rows
      } catch (error) {
        console.log(error)
      }
    },
    // 删除员工
    hDel(id) {
      this.$confirm('确认要删除吗?').then(async() => {
        const res = await delEmployee(id)
        console.log(res)
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        // 重新渲染
        this.loadEmployees()
      }).catch(error => {
        console.log(error)
      })
    },
    hResetForm() {
      this.$refs.addRef.resetForm()
    },
    hSuccess() {
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.loadEmployees()
      this.showDialog = false
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.loadEmployees()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployees()
    },
    // 格式聘用形式的函数
    formOfEmploymetnFormat(data) { // data=> 1||2
      // 将传入的1||2 转化为 正式 || 非正式
      // 一定要返回格式化的数据
      return hireType[data] || '未知'
    },
    // 获取员工列表
    async loadEmployees() {
      try {
        const res = await getEmployees(this.page, this.size)
        console.log(res)
        // 保存到data函数中
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>
